import { createSlice, createAsyncThunk, PayloadAction } from "@reduxjs/toolkit";
import { ListItem } from "../home/homeSlice";

interface CarState {
  data: CarItemType[];
}

interface CarItemType {
  title: string;
  id: string;
  desc: string;
  url: string;
  price: number;

  count: number;
  isChecked: boolean;
}

const initialState: CarState = {
  data: [],
};

const carSlice = createSlice({
  name: "car",
  initialState,
  reducers: {
    addCar(state, action: PayloadAction<ListItem>) {
      const item = state.data.find((v) => v.id === action.payload.id);
      if (item) {
        item.count++;
      } else {
        state.data.push({
          ...action.payload,
          count: 1,
          isChecked: false,
        });
      }
    },
    addCarItemCount(state, action: PayloadAction<ListItem>) {
      const item = state.data.find((v) => v.id === action.payload.id);
      if (item) item.count++;
    },
    subCarItemCount(state, action: PayloadAction<ListItem>) {
      const item = state.data.find((v) => v.id === action.payload.id);
      if (item) item.count--;
    },
    deleteCarItemCount(state, action: PayloadAction<ListItem>) {
      state.data = state.data.filter((v) => v.id !== action.payload.id);
    },
		switchCarItemCheck(state, action: PayloadAction<ListItem>) {
			const item = state.data.find((v) => v.id === action.payload.id);
      if (item) item.isChecked = !item.isChecked;
		},
		switchAllCarItemCheck(state, action: PayloadAction<boolean>) {
			state.data.forEach(v => v.isChecked = action.payload)
		}
  },
});

export const { addCar, addCarItemCount, subCarItemCount, deleteCarItemCount, switchCarItemCheck, switchAllCarItemCheck } = carSlice.actions;
export default carSlice;
